package tcpFirmware.controller;

import tcpFirmware.ResponseBody;
import tcpFirmware.Routes;
import tcpFirmware.Type;
import tcpFirmware.model.DBHelper;

import java.io.IOException;
import java.net.Socket;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

public class BalanceController {
    @Routes(route="balance_invest")
    public void invest(Socket socket, HashMap<String,String> head, HashMap<String,String> form) {
        float money=Float.parseFloat(form.get("money"));
        String username=form.get("username");
        Connection connection = new DBHelper().getConnection();
        try {
            Statement statement=connection.createStatement();
            ResultSet rs=statement.executeQuery("select * from Users where username='"+username+"'");
            rs.next();
            if(rs.getString("username").equals(username)) {
                ResponseBody responseBody = new ResponseBody(socket);
                int i=statement.executeUpdate("update Users set thebalance=thebalance+"+money+" where username='"+username+"'");
                if(i==1) {
                    responseBody.setHeader("充值状态","充值成功").setType(Type.text.type);
                }else {
                    responseBody.setHeader("充值状态","充值失败").setType(Type.text.type);
                }
                responseBody.sendResponse();
            }
        } catch (SQLException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Routes (route="balance_query")
    public void query(Socket socket, HashMap<String,String> head,HashMap<String,String> form) {
        String username=form.get("username");
        Connection connection = new DBHelper().getConnection();
        try {
            Statement statement=connection.createStatement();
            ResultSet rs=statement.executeQuery("select * from Users where username='"+username+"'");
            rs.next();
            if(rs.getString("username").equals(username)) {
                ResponseBody responseBody = new ResponseBody(socket);
                responseBody.setHeader("查询结果", "查询成功").setType(Type.text.type).setData("余额", String.valueOf(rs.getFloat("thebalance")));
                responseBody.sendResponse();
            }
        } catch (SQLException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
